﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IBuproRoleProvider.cs" company="">
//   Copyright (c) 2010/2011 All Right Reserved
// </copyright>
// <summary>
//   Contains IBuproRoleProvider interface declaration.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using iBuproModel.Repositories;

namespace iBuproModel.Providers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.Security;

    public class IBuproRoleProvider : RoleProvider
    {
        private Entities context;
        private Repositories.RepositoryService repositoryService;
        private ContextService contextService;

        public IBuproRoleProvider()
        {

            this.context = ContextService.GetInstance;
            repositoryService = new RepositoryService();
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
            get
            {
                return "ibupro";
            }

            set
            {
                throw new NotImplementedException();
            }
        }

        public override void CreateRole(string roleName)
        {
            try
            {
                Role role = new Role();
                role.Name = roleName;
                context.Roles.AddObject(role);

                context.SaveChanges();
            }
            catch
            {
                throw new Exception("Cannot create role");
            }
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            try
            {
                int count = context.Roles.Where(r => r.Name == roleName).Count();
                if (count == 0)
                    return false;


                if (throwOnPopulatedRole == true)
                {
                    int countUsers = context.Roles.Where(r => r.Name == roleName).SingleOrDefault().Users.Count();
                    if (countUsers != 0)
                        throw new Exception("Cannot delete role with existing users");
                }

                RemoveAllUsersInRole(roleName);
                context.Roles.DeleteObject(context.Roles.Where(r => r.Name == roleName).SingleOrDefault());
                
                context.SaveChanges();
                return true;
            }
            catch
            {
                throw new Exception("Cannot delete role: " + roleName);
            }
            
               
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            try
            {
                List<string> roles = (from r in context.Roles select r.Name).ToList();
                return roles.ToArray();
            }
            catch
            {
                throw new Exception("Cannot get roles");
            }
        }

        public override string[] GetRolesForUser(string username)
        {
            
            try
            {
                if (username == null)
                {
                    throw new Exception("Username cannot be null");
                }
                List<Role> roles = context.Users.Where(u => u.Username == username).SingleOrDefault().Roles.ToList();
                List<string> names = (from r in roles
                                     select r.Name).ToList<string>();
                                         
                
                return names.ToArray();
            }
            catch
            {
                throw new Exception("Cannot get roles");
            }
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            try
            {
                int count = context.Roles.Where(r => r.Name == roleName).SingleOrDefault().Users.Where(u => u.Username == username).Count();
                if (count > 0)
                    return true;
                else return false;
            }
            catch
            {
                throw new Exception("IsUserInRole method error");
            }
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            try
            {
                int count = context.Roles.Where(r => r.Name == roleName).Count();
                if (count > 0)
                    return true;
                else return false;
            }
            catch
            {
                throw new Exception("Cannot get check role");
            }
        }

        public void RemoveAllUsersInRole(string roleName)
        {
            try
            {
                if (!RoleExists(roleName))
                    throw new Exception("Role does not exist");
                Role role = context.Roles.Where(r => r.Name == roleName).SingleOrDefault();

                List<User> delete = new List<User>();

                foreach (User user in role.Users)
                {
                    delete.Add(user);
                }

                foreach (User user in delete)
                {
                    context.Users.DeleteObject(user);
                }

                role.Users.Clear();

                context.SaveChanges();
            }
            catch
            {
                throw new Exception("Cannot remove all users in role");
            }
        }

    }
}
